package com.shopping.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping.common.Result;
import com.shopping.dto.ProductDTO;
import com.shopping.dto.ProductQueryDTO;
import com.shopping.entity.Product;
import com.shopping.service.ProductService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/api/product")
public class ProductController {

    @Resource
    private ProductService productService;

    @GetMapping("/list")
    public Result<Page<ProductDTO>> getProductList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) BigDecimal minPrice,
            @RequestParam(required = false) BigDecimal maxPrice) {
        ProductQueryDTO queryDTO = new ProductQueryDTO();
        queryDTO.setPage(page);
        queryDTO.setSize(size);
        queryDTO.setName(name);
        queryDTO.setType(type);
        queryDTO.setMinPrice(minPrice);
        queryDTO.setMaxPrice(maxPrice);
        return Result.success(productService.getProductList(queryDTO));
    }

    @GetMapping("/recommended")
    public Result<List<ProductDTO>> getRecommendedProducts() {
        return Result.success(productService.getRecommendedProducts());
    }

    @GetMapping("/type/{type}")
    public Result<List<ProductDTO>> getProductsByType(@PathVariable String type) {
        return Result.success(productService.getProductsByType(type));
    }

    @GetMapping("/search")
    public Result<List<ProductDTO>> searchProducts(@RequestParam String keyword) {
        return Result.success(productService.searchProducts(keyword));
    }

    @GetMapping("/{id}")
    public Result<ProductDTO> getProductDetail(@PathVariable Long id) {
        return Result.success(productService.getProductById(id));
    }

    @PostMapping
    public Result<ProductDTO> addProduct(@RequestBody Product product) {
        return Result.success(productService.createProduct(product));
    }

    @PutMapping("/{id}")
    public Result<ProductDTO> updateProduct(@PathVariable Long id, @RequestBody Product product) {
        return Result.success(productService.updateProduct(id, product));
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteProduct(@PathVariable Long id) {
        productService.deleteProduct(id);
        return Result.success();
    }

    @PutMapping("/stock")
    public Result<Boolean> updateStock(@RequestParam Long productId, @RequestParam Integer quantity) {
        return Result.success(productService.updateStock(productId, quantity));
    }
}